//
//  WKShuangyuSuccessViewController.m
//  V-Learn
//
//  Created by Apple on 2019/3/18.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "WKShuangyuSuccessViewController.h"
//富文本
#import "ZSDTCoreTextTools.h"
#import "UIImageView+WebCache.h"
static NSString *kIdentifier = @"kIdentifier";
static NSString *kDouYinIdentifier = @"ImageTextIdentifier";
#import "LBCoureseDetailVC.h"
#import "LBCourseOutputDTOListModel.h"

@interface WKShuangyuSuccessViewController ()<UITableViewDelegate,UITableViewDataSource,DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>
@property (nonatomic, strong) LBCourseOutputDTOListModel *model;
@property (nonatomic, strong) UITableView *tableView;
//普通单元格与富文本单元格
@property (nonatomic, copy) NSString *cellID_Normal;
@property (nonatomic, copy) NSString *cellID_DTCoreText;

//类似tabelView的缓冲池，用于存放图片大小
@property (nonatomic, strong) NSCache *imageSizeCache;
@property (nonatomic,strong)NSCache *cellCache;
//表视图数据源
@property (nonatomic, strong) NSArray  *dataSourceArray;
@property (nonatomic, strong) NSMutableArray  *htmlArray;

@property (nonatomic,assign)BOOL isScrolling;
@property (nonatomic, strong) UIButton *shoppingButton;/**立即购买*/
@property (nonatomic, strong) UILabel *failLab;
@property (nonatomic, strong) UILabel *shopLab;
@end

@implementation WKShuangyuSuccessViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //请求数据
    [self requestdata];
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    //使用课时详情判断 是否购买过课程
//    [MBProgressHUD showSuccess:@"申请成功!" toView:self.view];

}
- (void)requestdata{
//    WKCourseListDetail_WKURL
    [WYHXNetWorkManager get:WKCourseListDetail_WKURL params:@{@"canNullToken":[UserModel getUserModel].token,@"courseId":self.courseId} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        NSDictionary *dict = (NSDictionary *)responseObj;
        NSDictionary *data = dict[@"data"];
        if ([code integerValue]==200) {
            self.model = [LBCourseOutputDTOListModel mj_objectWithKeyValues:dict[@"data"]];
            if ([self.model.isPay isEqualToString:@"1"]) {
                self.shoppingButton.hidden = YES;
                self.shopLab.hidden = NO;
                self.failLab.hidden = NO;
                //购买成功添加富文本到数组
                    [self.htmlArray addObject:self.resultContent];//添加富文本到数组
                
            }else{
                self.shoppingButton.hidden = NO;
                self.shopLab.hidden = NO;
                self.failLab.hidden = NO;
            }
            [self.tableView reloadData];
        }
    }];
}
- (void)setupUI{
    self.navigationItem.title = @"申请结果";
    [self.view addSubview:self.tableView];
    UIView *headerView = [UIView new];
//    self.tableView.tableHeaderView = headerView;r
    headerView.frame = CGRectMake(0, 0, ScreenW, 319);
    
    UIImageView *icon = [[UIImageView alloc] init];
    [headerView addSubview:icon];
    [icon makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(75);
        make.centerX.mas_equalTo(headerView);
        make.size.mas_equalTo(CGSizeMake(156, 130));
    }];
    icon.image = [UIImage imageNamed:@"wk_success"];

    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UILabel *failLab = [UILabel labelWithText:@"恭喜你申请成功，加油~" andTextColor:rgb(233,84,18) andName:nil andFontSize:15*kScaleFit];
    
    self.failLab = failLab;
    [headerView addSubview:failLab];
    [failLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(icon.mas_bottom).mas_equalTo(20*kScaleFit);
        make.centerX.mas_equalTo(headerView);
    }];
    
    UILabel *shopLab = [UILabel labelWithText:@"购买课程可加入微信群" andTextColor:rgb(51,51,51) andName:nil andFontSize:15*kScaleFit];
    [headerView addSubview:shopLab];
    self.shopLab = shopLab;
    [shopLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(failLab.mas_bottom).mas_equalTo(7*kScaleFit);
        make.centerX.mas_equalTo(headerView);
    }];
    
    UIView *footer = [UIView new];

    footer.frame = CGRectMake(0, 0, ScreenW, 60);
    UIButton *btn = [[UIButton alloc] init];
    self.shoppingButton = btn;
    [btn setTitle:@"立即购买" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setBackgroundImage:LBImage(@"wk_shadow_btn") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickShopping:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(45);
        make.top.mas_equalTo(10);
    }];
    self.tableView.tableHeaderView = headerView;
    self.tableView.tableFooterView = footer;
    
    self.cellID_Normal = @"UITableViewCellID";
    self.cellID_DTCoreText = @"DTCoreTextTableViewCellID";
    

    _imageSizeCache = [[NSCache alloc] init];
    _cellCache = [[NSCache alloc] init];
    _cellCache.totalCostLimit = 10;
    _cellCache.countLimit = 10;
}
- (void)clickShopping:(UIButton *)sender{
    
    LBCoureseDetailVC *courseDetailVC = [[LBCoureseDetailVC alloc] init];
    if (self.courseId==nil) {
        return;
    }
    courseDetailVC.courseId = self.courseId;
    courseDetailVC.type = @"1";
    courseDetailVC.jumpType = @"6";//和正常的支付区分开
    [self.navigationController pushViewController:courseDetailVC animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.htmlArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZSDTCoreTextCell *dtCell = (ZSDTCoreTextCell *) [self tableView:tableView prepareCellForIndexPath:indexPath];
    return dtCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self tableView:tableView prepareCellForIndexPath:indexPath];
    return [cell requiredRowHeightInTableView:tableView];
}
- (NSMutableArray *)htmlArray{
    if (!_htmlArray) {
        _htmlArray = [NSMutableArray array];
    }
    return _htmlArray;
}

- (void)reloadCurrentCell{
    //如果当前表视图在滑动就不执行刷新，因为滑动时候会自动调用表视图的刷新方法
    if (self.isScrolling) {
        return;
    }
    //如果当前表视图没有在滑动，就手动刷新当前在屏幕显示的单元格
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if(indexPaths){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        });
    }
}
//显示动画，表视图停止滑动之后调用；没有动画此方法不调用
//- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
//    _isScrolling = NO;
//   [self reloadCurrentCell];
//}
//
////手指拖动表视图，表视图停止滑动之后调用
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    _isScrolling = NO;
//    [self reloadCurrentCell];
//}
#pragma mark - private Methods
//创建富文本单元格，并更新单元格上的数据
- (ZSDTCoreTextCell *)tableView:(UITableView *)tableView prepareCellForIndexPath:(NSIndexPath *)indexPath{
    NSString *key = [NSString stringWithFormat:@"dtCoreTextCellKEY%ld", (long)indexPath.row];
    ZSDTCoreTextCell *cell = [_cellCache objectForKey:key];
    
    if (!cell){
        //    cell = [self.tableView dequeueReusableCellWithIdentifier:_cellID_DTCoreText];
        //        if (!cell) {
        cell = [[ZSDTCoreTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellID_DTCoreText];
        //        }
        cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.hasFixedRowHeight = NO;
        cell.textDelegate = self;
        cell.attributedTextContextView.shouldDrawImages = YES;
        //记录在缓存中
        [_cellCache setObject:cell forKey:key];
    }
    //2.设置数据
    //2.1为富文本单元格设置Html数据
    [cell setHTMLString:self.htmlArray[indexPath.row]];
    //2.2为每个占位图(图片)设置大小，并更新
    for (DTTextAttachment *oneAttachment in cell.attributedTextContextView.layoutFrame.textAttachments) {
        NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
        if (sizeValue) {
            cell.attributedTextContextView.layouter=nil;
            oneAttachment.displaySize = [sizeValue CGSizeValue];
            [cell.attributedTextContextView relayoutText];
        }
    }
    [cell.attributedTextContextView relayoutText];
    return cell;
}
//对于无宽高懒加载得到的图片，缓存记录其大小,然后执行表视图更新
- (void)lazyImageView:(ZSDTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size{
    BOOL needUpdate = NO;
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    /* update all attachments that matchin this URL (possibly multiple
     images with same size)
     */
    for (DTTextAttachment *oneAttachment in [lazyImageView.textContentView.layoutFrame textAttachmentsWithPredicate:pred]){
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero)){
            oneAttachment.originalSize = size;
            NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
            if (!sizeValue) {
                //将图片大小记录在缓存中，但是这种图片的原始尺寸可能很大，所以这里设置图片的最大宽
                //并且计算高
                CGFloat aspectRatio = size.height / size.width;
                CGFloat width = ZSToolScreenWidth - 15*2;
                CGFloat height = width * aspectRatio;
                CGSize newSize = CGSizeMake(width, height);
                [_imageSizeCache setObject:[NSValue valueWithCGSize:newSize]forKey:url];
            }
            needUpdate = YES;
        }
    }
    
    if (needUpdate){
        //有新的图片尺寸被缓存记录的时候，需要刷新表视图
        //[self reloadCurrentCell];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadCurrentCell) object:nil];
        self.isScrolling = NO;
        [self performSelector:@selector(reloadCurrentCell) withObject:nil afterDelay:0.2];
    }
}
#pragma mark - DTAttributedTextContentViewDelegate
//对于没有在Html标签里设置宽高的图片，在这里为其设置占位
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    if([attachment isKindOfClass:[DTImageTextAttachment class]]){
        ZSDTLazyImageView *imageView = [[ZSDTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.textContentView = attributedTextContentView;
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}

@end
